package com.gaohc.framework.config.encrypt;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gaohc.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * response 响应参数统一加密处理拦截器
 *
 * @author gbx
 */
@ControllerAdvice
@Slf4j
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Map<String, Object> resMap = new HashMap<>(16);
        try {
            String path = serverHttpRequest.getURI().getPath();
            if (StringUtils.isNotBlank(path)) {
                ObjectMapper objectMapper = new ObjectMapper();
                String json = objectMapper.writeValueAsString(body);
                log.info("====》 响应路径：" + path + "，原实际返回参数：" + json);
                if (StringUtils.isNotBlank(json) && !GbxDispatcherServlet.noCheckUrl.contains(path)) {
                    String dataHex = SM4Util.encrypt(json);
                    resMap.put("data", dataHex);
                }
            }
            log.info("====》 响应路径：" + path + "，实际响应参数:{}", JSONObject.toJSONString(resMap, SerializerFeature.WriteMapNullValue));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        if (ObjectUtils.isNotEmpty(resMap)) {
            return resMap;
        }
        return body;
    }
}
